/**
 *
 */
package com.bocloud.config;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;


/**
 * 数据库连接配置类
 */

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = "com.bocloud.mappers", sqlSessionTemplateRef = "loginSqlSessionTemplate")
public class LogindbConfig {
    Logger log = LoggerFactory.getLogger(LogindbConfig.class);

    @Bean(name = "loginDataSource")
    @ConfigurationProperties(prefix = "spring.datasource")
    @Primary
    public DataSource loginDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "loginSqlSessionFactory")
    @Primary
    public SqlSessionFactory loginSqlSessionFactory(@Qualifier("loginDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setTypeAliasesPackage("com.bocloud.model");
        bean.setVfs(SpringBootVFS.class);

        //添加XML目录
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            bean.setMapperLocations(resolver.getResources("classpath:mapper/*.xml"));
            return bean.getObject();
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new RuntimeException(e);
        }
    }


    @Bean(name = "loginTransactionManager")
    @Primary
    public DataSourceTransactionManager loginTransactionManager(@Qualifier("loginDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "loginSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate newsSqlSessionTemplate(@Qualifier("loginSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
